package br.ufrj.cg.controller;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import br.ufrj.cg.model.StampBackgroundImage;
import br.ufrj.cg.model.StampImage;

/**
 * 
 * @author Diego Martins
 * 
 */
public class StampXMLWriter {

	StampBackgroundImage stampBackgroundImage;
	Document xmlOutput;

	public StampXMLWriter(StampBackgroundImage paramStampBackgroundImage)
			throws ParserConfigurationException {

		stampBackgroundImage = paramStampBackgroundImage;
		
		DocumentBuilderFactory docFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder docBuilder;
		docBuilder = docFactory.newDocumentBuilder();
		xmlOutput = docBuilder.newDocument();

	}

	public void prepareXML() {
		Element rootElement = xmlOutput.createElement("stamp");
		xmlOutput.appendChild(rootElement);
		
		Element stampBackground = xmlOutput.createElement("stampBackground");
		rootElement.appendChild(stampBackground);
		
		stampBackground.setAttribute("filePath", stampBackgroundImage.getImagePath());
		
		for(StampImage s : stampBackgroundImage.getChildren())
		{
			Element stampImageElement = xmlOutput.createElement("stampImage");
			stampBackground.appendChild(stampImageElement);
			
			
			
			stampImageElement.setAttribute("filePath", s.getImagePath());
			stampImageElement.setAttribute("x", String.valueOf(s.getxPosition()));
			stampImageElement.setAttribute("y", String.valueOf(s.getyPosition()));
			
			
		}
	}

	public void write(String paramOutputFileName) {

		prepareXML();

		try {
			TransformerFactory transformerFactory = TransformerFactory
					.newInstance();
			Transformer transformer;
			transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(xmlOutput);
			StreamResult result = new StreamResult(
					new File(paramOutputFileName));

			transformer.transform(source, result);

			System.out.println("File saved!");
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}

	}

	public static void main(String argv[]) {

	}
}
